<script setup>
import { ElMessage,ElMessageBox  } from 'element-plus'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue'
import { ref ,onBeforeMount, reactive, toRefs, computed} from 'vue';
import { da } from 'element-plus/es/locales.mjs';
import { listHandler } from '../../api/generic.js';
import { deleteTableRow } from '../../utils/utils';
import Table from '../components/Table.vue';
import { object2List,list2Object } from '../../utils/utils';
// import DialogYaml from '../components/DialogYaml.vue';
// import { obj2Yaml } from '../../utils/utils';
import { updateIngressHandler as updateHandler, createIngressHandler as createHandler,getIngressClassListHandler } from '../../api/ingress';
import { getServiceListHandler } from '../../api/service.js';
import { getSecretListHandler } from '../../api/secret.js';
import {useRouter} from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})

const data = reactive({
  clusterId: '',
  namespace: '',
  item: {
    apiVersion: 'networking.k8s.io/v1',
    kind: 'Ingress',
    metadata: {
      name: '',
      namespace: '',
      labels: {},
      annotations: {}
    },
    spec: {
      // ingressClassName: '',
      rules: [],
    }
    },
    path:  {
      backend: {
        service: {
          name: "",
          port: {
            number: null
          },
        },
      },
      path: "",
      pathType: "Prefix",
    },
  options: {
    serviceList:[],
    tlsSecretList: [],
    serviceSelected:[],
    ingressClassList: [],
    labelList:[],
    annotationsList:[],
    podLabelList: [],
    rules: {
      name: [
            {required: true, message: '请输入Ingress名称', trigger: 'blur'}
        ],
      path: [
          {required: true, message: '请输入路径', trigger: 'blur'},
          {pattern: '^(?=/)', message: '路径必须以 / 开头', trigger: 'blur'}
      ],
      serviceName: [
          {required: true, message: '请选择代理的服务', trigger: 'blur'},
      ],
      port: [
          {required: true, message: '请选择端口', trigger: 'blur'},
      ],
    },
    pathType:[
      {
        value: 'Exact',
        label: '精确匹配'
      },
      {
        value: 'Prefix',
        label: '前缀匹配'
      },
      {
        value: 'ImplementationSpecific',
        label: '取决于IngressClass'
      },
    ]
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
let yamlContent = ref('')
let showDetail = ref(false)

const submitRollback = (msg)=>{ 
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
    }
  )
    .then(() => {
      //跳转到对应的列表页
      router.replace({
        path: '/ingress/list',
        query: {
          clusterId: data.clusterId,
          namespace: data.namespace
        }
      })
    })
    .catch(() => {
      return
    })
}

const submitHandler = (tag) => {
  console.log('tag:', tag)
  console.log('item:', data.item)
  //把list转成object
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationsList)
  if (tag == 'yaml') {
    // 首先要把json转成yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item,
    }
    if (props.method != "Update") {
        // 创建用户，异步的
        createHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
          // loading.value = false
          // emits('rollback')
        })
  } else {
      // 创建用户，异步的
      updateHandler(postData).then((response)=>{
          // console.log("response:", response)
          // ElMessage({
          //         message: response.data.message,
          //         type: 'success',
          // })
          submitRollback(response.data.message)
      })
    }
  }

}

const submit = (tag)=> {
    itemRef.value.validate((valid)=>{
        // valid => true
        if(!valid){
        ElMessage({
                    message: "请完善表单内容",
                    type: 'warning',
                })
        }else {
          submitHandler(tag)
        }
    })
}
const namespaceChangeHandler = (clusterId, namespace)=>{
  console.log('namespaceChangeHandler:', clusterId, namespace)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
  //刷新一下资源列表
    getServiceist()
}
const getServiceist = async()=>{
  console.log("获取资源列表:",data.clusterId, data.namespace)
  await getServiceListHandler({clusterId:data.clusterId, namespace:data.namespace})
  .then((res)=>{
    console.log("获取资源列表:",res.data.data.items)
    data.options.serviceList = res.data.data.items
  })
}
const ingressClassVisibleChanged = (visible) =>{
    if (!visible){return}
    const getListParas = {
        clusterId: data.clusterId,
    }
    getIngressClassListHandler(getListParas).then(
        (res) => {
          data.options.ingressClassList = res.data.data.items
        }
      )
}
//添加路由
const addRule = ()=>{ 
  const rule = { 
    host: '',
    http: {
      paths: [
        JSON.parse(JSON.stringify(data.path))
      ],
    }
  }
  data.item.spec.rules.push(JSON.parse(JSON.stringify(rule)))
}

const addPath = (ruleIndex) =>{
  data.item.spec.rules[ruleIndex].http.paths.push(JSON.parse(JSON.stringify(data.path)))
}
const getServicePort = computed(()=>(serviceName)=>{
  console.log("获取当前Service的端口配置:",serviceName)
  for (let s = 0;s<data.options.serviceList.length;s++){
    if (data.options.serviceList[s].metadata.name === serviceName){
      const ports = []
      data.options.serviceList[s].spec.ports.forEach((port)=>{
        if (ports.indexOf(port.port) == -1){
            ports.push(port.port)
        }
      })
      return ports
    }
  }
  // data.options.serviceList.forEach((service)=>{
  //   if (service.metadata.name == serviceName){
  //     return service.spec.ports
  //   }
  // })
})

//获取tls类型的secret
const getTLSSecretList = (visible)=>{
  console.log("visible:",visible)
  // 展开的时候去查询items
  if (visible) {
    // 调用查询列表的函数
    const getData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      labelSelector: '',
      fieldSelector: 'type=kubernetes.io/tls'
    }
    getSecretListHandler(getData).then(
      (res) => {
        data.options.tlsSecretList = res.data.data.items
        console.log(data.options.tlsSecretList)
      }
    )
  }
}

const addTls = ()=>{ 
  if (data.item.spec.tls == undefined){
    data.item.spec.tls = []
  }
  const tlsConfig = { 
    hosts: [],
    secretName: ''
  }
  data.item.spec.tls.push(tlsConfig)
}


onBeforeMount(()=>{
  if (props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationsList = object2List(data.item.metadata.annotations)
    //拿到已经配置的service列表
    //循环rules 拿到路由规则
    data.item.spec.rules.forEach((rule)=>{
      //循环path拿到service name
      rule.http.paths.forEach((path)=>{
        if (data.options.serviceSelected.indexOf(path.backend.serviceName) == -1){
          data.options.serviceSelected.push(path.backend.service.name)
        }
      })
    })
  }
})  
const {options,item,clusterId,namespace} = toRefs(data)

</script>

<template>
  <CreateOrEditFrame
  :namespace-readonly="props.method == 'Update'"
  :cluster-readonly="props.method == 'Update'"
  @namespace-changed-rollback="namespaceChangeHandler"
  >
  <!-- 头部插入内容 -->
   <template #header>
<!-- 选择资源名称 -->
    <el-select style="margin-left: 10px; width: 180px;" 
    v-model="options.serviceSelected" 
    value-key="metadata.name"
    multiple collapse-tags
    placeholder="选择代理的Service"
    >
        <el-option v-for="t in options.serviceList" 
        :key="t.metadata.name" 
        :label="t.metadata.name" 
        :value="t.metadata.name">
        </el-option>
    </el-select>
   </template>
   <template #main>
    <el-form :model="item"
    ref="itemRef">
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="基本配置" name="basic" style="height: 240px;">
        <el-row :gutter="20">
          <el-col :span="6">
              <el-form-item  :rules="options.rules.name" label="Ingress名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'" v-model="item.metadata.name"></el-input>
              </el-form-item>
          </el-col>
          <!-- 选择ingressClassName -->
          <el-col :span="6">
              <el-form-item  label="选择IngressClass" prop="">
                <el-select @visible-change="ingressClassVisibleChanged" clearable v-model="item.spec.ingressClassName" placeholder="选择ingressClass" @change="selectChanged">
                    <el-option
                    v-for="s in options.ingressClassList"
                    :key="s.metadata.name"
                    :label="s.metadata.name"
                    :value="s.metadata.name"
                    />
                </el-select>
              </el-form-item>
          </el-col>
        </el-row>

      </el-tab-pane>
      <el-tab-pane 
      label="路由配置" 
      name="rules" 
      >
      <el-tabs tab-position="left">
        <el-tab-pane  label="域名配置">
        <!-- 第一个table展示和配置域名 -->
          <el-table :data="item.spec.rules" border height="360px">
              <el-table-column prop="host" label="域名" width="240" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.host" placeholder="请输入域名"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="http" label="路径配置" width="" align="center">
                <template #default="scope">
                  <el-table :data="scope.row.http.paths" border height="120px">
                      <el-table-column prop="path" label="路径" width="" align="center">
                        <template #default="pathScope">
                          <el-form-item :rules="options.rules.path" required :prop="('spec.rules.'+scope.$index+'.http.paths.'+pathScope.$index+'.path')">
                            <el-input v-model="pathScope.row.path" placeholder="访问路径"></el-input>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="backend.service.name" label="选择代理服务" width="240" align="center">
                        <template #default="pathScope">
                          <el-form-item :rules="options.rules.serviceName" required :prop="('spec.rules.'+scope.$index+'.http.paths.'+pathScope.$index+'.backend.service.name')">
                            <el-select v-model="pathScope.row.backend.service.name" placeholder="选择代理的服务">
                              <el-option 
                              v-for="s in options.serviceSelected" 
                              :key="s" 
                              :label="s" 
                              :value="s">
                              </el-option>
                          </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="backend.service.port.number" label="代理端口" width="180" align="center">
                        <template #default="pathScope">
                          <el-form-item :rules="options.rules.port" required :prop="('spec.rules.'+scope.$index+'.http.paths.'+pathScope.$index+'.backend.service.port.number')">
                            <el-select v-model="pathScope.row.backend.service.port.number" placeholder="选择代理的服务">
                              <el-option 
                              v-for="s in getServicePort(pathScope.row.backend.service.name)" 
                              :key="s" 
                              :label="s" 
                              :value="s">
                              </el-option>
                          </el-select>
                          </el-form-item>
                        </template>
                      </el-table-column>
                      <el-table-column prop="pathType" label="匹配模式" width="180" align="center">
                        <template #default="pathScope">
                          <el-select v-model="pathScope.row.pathType" placeholder="路由匹配模式">
                              <el-option 
                              v-for="pt in options.pathType" 
                              :key="pt.value" 
                              :label="pt.label" 
                              :value="pt.value">
                              </el-option>
                          </el-select>
                        </template>
                      </el-table-column>
                      <el-table-column width="140" align="center" fixed="right">
                        <template #header>
                          <el-button type="primary" link @click="addPath(scope.$index)">添加</el-button>
                        </template>
                        <template #default="pathScope">
                          <el-button type="warning" link @click="deleteTableRow(item.spec.rules[scope.$index].http.paths,pathScope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column width="140" align="center" fixed="right">
                <template #header>
                  <el-button type="primary" link @click="addRule()">添加</el-button>
                </template>
                <template #default="scope">
                  <el-button type="warning" link @click="deleteTableRow(item.spec.rules,scope.$index)">删除</el-button>
                </template>
              </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane  label="证书配置">
            <el-table :data="item.spec.tls" border height="360px">
            <el-table-column prop="" label="选择域名" width="" align="center">
                <template #default="scope">
                    <el-select style="width: 100%;" multiple filterable v-model="scope.row.hosts" placeholder="选择域名">
                      <el-option 
                      v-for="s in item.spec.rules" 
                      :key="s.host" 
                      :label="s.host" 
                      :value="s.host">
                      </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="" label="证书" width="240" align="center">
                <template #default="scope">
                    <el-select @visible-change="getTLSSecretList" v-model="scope.row.secretName" placeholder="选择域名证书">
                      <el-option 
                      v-for="s in options.tlsSecretList" 
                      :key="s.metadata.name" 
                      :label="s.metadata.name" 
                      :value="s.metadata.name">
                      </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column width="140" align="center" fixed="right">
                <template #header>
                  <el-button type="primary" link @click="addTls()">添加</el-button>
                </template>
                <template #default="scope">
                  <el-button type="warning" link @click="deleteTableRow(item.spec.tls,scope.$index)">删除</el-button>
                </template>
              </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    
      </el-tab-pane>
      <el-tab-pane label="注释及标签" name="labels">
        <el-tabs v-model="labelConfig" tabPosition="left">
            <el-tab-pane label="标签配置" name="labels">
              <Table :list="options.labelList"></Table>
            </el-tab-pane>
            <el-tab-pane label="注释配置" name="annos">
              <Table :list="options.annotationsList"></Table>
            </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>

    <!-- yaml,创建 -->
     <el-form-item class="button-container">
     <div class="button-wrapper"> <!-- 新增包裹层 -->
      <el-button @click="submit('yaml')">Yaml</el-button>
      <el-button type="primary" @click="submit()">
        {{ props.method=="Update" ? "更新" : "创建" }}
      </el-button>
    </div>
  </el-form-item>
    </el-form>
   </template>

  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  :method="props.method"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
</template>

<style scoped>
.button-container {
  /* 去除表单组件默认内边距 */
  padding: 0 !important;
  text-align: center; /* 辅助居中 */
}

.button-wrapper {
  /* 弹性布局容器 */
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 按钮间距 */
  padding: 20px; /* 添加自定义内边距 */
  width: 100%; /* 占满父容器宽度 */
}
</style>
